package me.zd.tool.hardlink.service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesService {
    public static Properties loadFromResource(String path) {
        InputStream is = PropertiesService.class.getClassLoader().getResourceAsStream(path);
        if (is == null) {
            return null;
        }
        return loadFromInputStream(is);
    }

    public static Properties loadFromFile(File file) {
        try (FileInputStream fis = new FileInputStream(file)) {
            return loadFromInputStream(fis);
        } catch (IOException e) {
            return null;
        }
    }

    public static Properties loadFromInputStream(InputStream is) {
        Properties p = new Properties();
        try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) {
            p.load(isr);
            return p;
        } catch (IOException e) {
            return null;
        }
    }

    public static void writeToFile(Properties p, String path) throws IOException {
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8)) {
            p.store(osw, null);
        }
    }

    public static Map<String, String> toMap(Properties p) {
        if (p == null) {
            return new HashMap<>();
        }
        return p.stringPropertyNames().stream().collect(HashMap::new, (m, k) -> m.put(k, p.getProperty(k)), HashMap::putAll);
    }

    public static Properties toProperties(Map<String, String> map) {
        Properties p = new Properties();
        if (map != null) {
            map.forEach((k, v) -> {
                if (v != null) {
                    p.put(k, v);
                }
            });
        }
        return p;
    }
}
